package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.service.IDbBackupAndRecoverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class DbBackupAndRecoverServiceImpl implements IDbBackupAndRecoverService {
    @Autowired
    private ServletContext ctx;
    @Override
    public String backup() throws IOException {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String filename =  simpleDateFormat.format(date) + ".sql";
        String path = ctx.getRealPath("/static/database/"+ filename);
        Runtime runtime = Runtime.getRuntime();
        //-u后面是用户名，-p是密码-p后面最好不要有空格，-family是数据库的名字
        Process process = runtime.exec("mysqldump -u root -padmin crm");
        InputStream inputStream = process.getInputStream();//得到输入流，写成.sql文件
        InputStreamReader reader = new InputStreamReader(inputStream);
        BufferedReader br = new BufferedReader(reader);
        String s = null;
        StringBuffer sb = new StringBuffer();
        while ((s = br.readLine()) != null) {
            sb.append(s + "\r\n");
        }
        s = sb.toString();
        System.out.println(s);
        File file = new File(path);
        file.getParentFile().mkdirs();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(s.getBytes());
        fileOutputStream.close();
        br.close();
        reader.close();
        inputStream.close();
        return filename;
    }


    @Override
    public void recover(String filepath) {

        String stmt2 = "mysql -u root -padmin crm < " + filepath;
        String[] cmd = {"cmd", "/c", stmt2};

        try {
            Runtime.getRuntime().exec(cmd);
            System.out.println("数据已从 " + filepath + " 导入到数据库中");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
